#include "customcommandthread.h"
#include "framewindow.h"
#include "serialthread.h"

#include <QDebug>
#include <QDateTime>



CustomCommandThread::CustomCommandThread(FrameWindow *frameWindow)
{
    this->parent = frameWindow;
}

CustomCommandThread::~CustomCommandThread()
{
    quit();
    wait();

}



int CustomCommandThread::init()
{
    connect(this,&CustomCommandThread::sendData,parent,&FrameWindow::onSendCustom);
    connect(this,&CustomCommandThread::sendCustomResult,parent,&FrameWindow::onSendCustomResult);

    moveToThread(QThread::currentThread());

    COMMap = new QMap<QString,SerialPortsManager*>;

    foreach ( QString comName,parent->COMLists) {

        SerialPortsManager  *manager = new SerialPortsManager(parent);
        QSerialPort *COM = new QSerialPort();
        manager->serialPort = COM;

        COM->moveToThread(this);
        COMMap->insert(comName,manager);

    }

    return 0;
}



void CustomCommandThread::run()
{

    init();

    qDebug() << "CustomCommandThread run() started!";
    wait(5000);

    int loop = 0;
    int cmdIndex =0;

    QString COMName;


    //串口循环
    QMap<QString, SerialPortsManager*>::iterator iter1 = COMMap->begin();
    while (iter1 !=COMMap->end())
    {
        loop++;

        COMName = iter1.key();
        qDebug() << "串口名称： "<<COMName;
        iter1.value()->moveToThread(QThread::currentThread());

        iter1.value()->configCOM();
        iter1.value()->openCOM(COMName);


        /*
         * 命令循环
         */

        cmdIndex = 0;
        QLinkedList<ATCommandItem>::iterator iter2;
        for (iter2=parent->customCommands.begin();iter2!=parent->customCommands.end();iter2++)
        {

            if(!iter2->check){
                cmdIndex++;
                continue;
            }

            QString m;
            m.sprintf(" [%d-%d] ",loop,cmdIndex);


            emit sendData(COMName+m,iter2->atCommand);
            qDebug() <<QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss:zzz")<<COMName+m<<"发送：";
            qDebug() <<iter2->atCommand;

            iter1.value()->mutex.lock();

            iter1.value()->sendCOM(iter2->atCommand.toLocal8Bit());

            msleep(700);
            if (iter1.value()->waitForReceive(5000))
            {

                //从缓冲区中读取数据
                QByteArray buffer = iter1.value()->serialPort->readAll();

                qDebug() <<QDateTime::currentDateTime().toString("yyyyMMdd-hhmmss:zzz")<<COMName<<"接收：";
                qDebug() <<buffer;

                iter1.value()->newReceived=buffer;
                dealData(COMName,*iter2  ,iter1.value()->newReceived);

            }
            iter1.value()->mutex.unlock();

            cmdIndex++;
        }

        iter1.value()->closeCOM();

        iter1++; //
    }


}



int CustomCommandThread::dealData(QString COM,ATCommandItem  comm, QByteArray rec)
{
    int responseComm = 1;
    int responseStatus =1;
    QString send = comm.atCommand.simplified();

    QString recString;

    QString strRec;
    strRec.prepend(rec);
    strRec = strRec.trimmed();

    QStringList  strs =strRec.split(QRegExp("[\r\n]"),QString::SkipEmptyParts);

    //temp+=send;

    foreach (QString response, strs)
    {
        // send command
        if(send==response){
            qDebug() <<send<<" == "<<response;
            responseComm = 0;
        }

        if(comm.resposeGood ==response){
            responseStatus = 0;
        }
        recString += response+"  ";
    }

    emit sendCustomResult(COM,recString,responseComm);

    return 0;
}

